<?php
/**
 * Created by jinqiang on 2024/7/15 16:31.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Repository;


use http\Client\Request;
use Illuminate\Support\Facades\Cache;

class AntifakeRepository
{
    CONST APP_INFO = [
        'kz' => [
            'app_id' => "wx9c3413378b176673",
            'app_secret' => "df6c3c0b8b24c7f2addad7a00b1773db"
        ],
        'js' => [
            'app_id' => "wx58dc1c038e775523",
            'app_secret' => "0f6365329ae4b11761b35d819252d8c3"
        ]
    ];

    private $_sub = "kz";

    public function __construct($sub)
    {
        $this->_sub = $sub;
    }

    //登录凭证校验
    public static function jscode2session($sub, $code)
    {
        $appid = self::APP_INFO[$sub]['app_id'];
        $secret = self::APP_INFO[$sub]['app_secret'];
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
        $res = httpCurl($url, [], "get");
        return json_decode($res, true);
    }

    //获取access_token
    public static function getAccessToken($sub)
    {
        $cacheKey = "{$sub}_access_token";
        $accessTokenRes = Cache::get($cacheKey);
        if(empty($accessTokenRes)){
            $appid = self::APP_INFO[$sub]['app_id'];
            $secret = self::APP_INFO[$sub]['app_secret'];
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
            $resp = httpCurl($url, [], "get");
            $accessTokenRes = json_decode($resp, true);
            Cache::put($cacheKey, $accessTokenRes, now()->addSeconds(6000));
        }
        return $accessTokenRes;
    }

    public static function clearAccessToken($sub)
    {
        Cache::forget("{$sub}_access_token");
    }

    public static function getPhoneNumber($sub, $code)
    {
        $accessTokenRes = self::getAccessToken($sub);
        $url ="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={$accessTokenRes['access_token']}";
        $param = [
            "json" => json_encode(['code' => $code])
        ];
        $res = httpCurl($url, $param);
        return json_decode($res, true);
    }

    //获取小程序跳转链接
    public static function getScheme($sub)
    {
        $accessTokenRes = self::getAccessToken($sub);
        $param = [
            "json" => json_encode(['is_expire'=>false ,'expire_time'=>''])
        ];
        $url = "https://api.weixin.qq.com/wxa/generatescheme?access_token={$accessTokenRes['access_token']}";
        $res = httpCurl($url, $param);
        return json_decode($res, true);
    }
}
